<?php
namespace app\store\controller\wxapp;
use app\store\controller\Controller;
use app\store\model\CategoryServe as CategoryServeModel;

/**
 * 小程序服务类目管理
 */
class Category extends Controller
{
    /**
     * 类目列表
     */
    public function index()
    {
		$model = new CategoryServeModel;
        $list = $model->getList();
		return $this->fetch('index', compact('list'));	
    }

    /**
     * 删除
     */
    public function delete($category_serve_id)
    {
        $model = CategoryServeModel::get($category_serve_id);
        if (!$model->remove()) {
            $error = $model->getError() ?: '删除失败';
			return $this->renderError($error);
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 添加
     */
    public function add()
    {
		// 获取类目
        $category = $this->getCategory();
		if(!$category){
			$this->error('从微信端获取类目数据错误!', 'wxapp.category/index');
            return false;
		}
        if (!$this->request->isAjax()) {
            return $this->fetch('add', compact('category'));
        }
		if($this->store['wxapp']['source']['value']==10){
			return $this->renderError('非通过本平台快速注册的小程序此功能不可用， 添加时会有错误警告，请自行到微信公众平台添加');
		}
		$model = new CategoryServeModel;
		if ($model->add($this->postData('category'),$category)) {
            return $this->renderSuccess('添加成功', url('wxapp.category/index'));
        }
        $error = $model->getError() ?: '添加失败';
        return $this->renderError($error);
    }
	
	/**
     * 获取微信端可用服务类目
     */
    private function getCategory()
    {
        //同步微信端线下类目
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/wxopen/getallcategories?access_token='.$access_token;
		$result = json_decode(curl($url),true);
		if($result['errcode']==0){
			$category = $result['categories_list']['categories'];
			$new = []; //筛选后的类目
			//遍历一级类目
			foreach($category[0]['children'] as $value){
				//查找一级类目
				for($n=1;$n<sizeof($category);$n++){
					//如果找到该一级目录
					if($category[$n]['id']==$value){ 
						//判断是否有二级目录
						if(sizeof($category[$n]['children'])){
							$first['id'] = $category[$n]['id'];
							$first['name'] = $category[$n]['name'];
							//遍历二级目录
							$second = [];
							foreach($category[$n]['children'] as $value2){
								//查找二级目录
								for($m=$n;$m<sizeof($category);$m++){
									//如果找到该一级目录
									if($category[$m]['id']==$value2){
										$category[$m]['father_name'] = $category[$n]['name'];
										array_push($second,$category[$m]);
										break;
									} 
								}
							}
							//如果存在可用二级目录
							if(sizeof($second)){
								$first['children'] = $second;
								array_push($new,$first);
								break;
							}
						}
						
					}
				}
			}
			return $new;//返回类目结果
		}
		return false;//获取失败
    }

}
